package com.sxc.loglib;

import android.os.Build;
import android.os.SystemClock;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

/**
 * Create by sunxunchao on 2019/11/18
 */
public class CrashHelper implements Thread.UncaughtExceptionHandler {

    private DateFormat formatter;
    private String currentTime;

    public CrashHelper() {
        Thread.setDefaultUncaughtExceptionHandler(this);//设置该CrashHandler为系统默认的
        formatter = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss", Locale.CHINA);
        currentTime = formatter.format(new Date());
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        String deviceInfo = collectDeviceInfo();
        String crashInfo = collectCrashInfo(e);
        FileUtils.writeLogFile(currentTime + "\n" +
                        deviceInfo + "\n" +
                        crashInfo,
                LogConfig.getInstance().getCrashName());

        SystemClock.sleep(2000);//延迟2秒杀进程
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    private String collectCrashInfo(Throwable ex) {
        if (ex == null) return "";

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable throwable = ex.getCause();
        while (throwable != null) {
            throwable.printStackTrace(printWriter);
            throwable = throwable.getCause();//逐级获取错误信息
        }
        String crashInfo = writer.toString();
        printWriter.close();
        return crashInfo;
    }

    /**
     * 获取手机信息
     */
    private String collectDeviceInfo() {
        StringBuilder sb = new StringBuilder();
        //App版本
        sb.append("App Version: ");
        sb.append(BuildConfig.VERSION_NAME);
        sb.append("_");
        sb.append(BuildConfig.VERSION_CODE + "\n");

        //Android版本号
        sb.append("OS Version: ");
        sb.append(Build.VERSION.RELEASE);
        sb.append("_");
        sb.append(Build.VERSION.SDK_INT + "\n");

        //手机制造商
        sb.append("Vendor: ");
        sb.append(Build.MANUFACTURER + "\n");

        //手机型号
        sb.append("Model: ");
        sb.append(Build.MODEL + "\n");

        //CPU架构
        sb.append("CPU: ");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            sb.append(Arrays.toString(Build.SUPPORTED_ABIS));
        } else {
            sb.append(Build.CPU_ABI);
        }
        return sb.toString();
    }
}
